package com.example.springboot_jdk8.config;

import org.apache.catalina.Pipeline;
import org.apache.catalina.Valve;
import org.apache.catalina.valves.ErrorReportValve;
import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 自定义tomcat配置,禁止将400,404,500等错误详情堆栈,添加至响应体中展示
 */
@Order(2)
@Component
public class TomcatCustomizer implements WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> {
    @Override
    public void customize(ConfigurableTomcatWebServerFactory factory) {
        factory.addContextCustomizers((context) -> {
            Pipeline pipeline = context.getParent().getPipeline();
            Valve[] valves = pipeline.getValves();
            Arrays.stream(valves).filter(valve -> valve instanceof ErrorReportValve).forEach(valve -> {
                ErrorReportValve errorValve = (ErrorReportValve) valve;
                errorValve.setShowReport(false);
                errorValve.setShowServerInfo(false);
            });
        });
    }
}
